package com.jqq.threaduse.homework;

import java.util.Scanner;

/**
 * @author 姬倩倩
 * @version 1.0
 */
public class Homework01 {
    public static void main(String[] args) throws InterruptedException {
        A a = new A();
        a.start();
        B b = new B(a);
        b.start();

    }
}
//创建A线程类
class A extends Thread {
    private boolean loop = true;

    @Override
    public void run() {
        while (loop) {
            System.out.println("随机数=" + (int) (Math.random() * 100 + 1));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void setLoop(boolean loop) {
        this.loop = loop;
    }
}
//直到第2个线程从键盘读取了Q
class B extends Thread {
    public A a;
    public Scanner myScanner = new Scanner(System.in);
    public B(A a) {//构造器中直接传入A对象
        this.a = a;
    }

    @Override
    public void run() {
        while (true) {
            //接收用户的输入
            System.out.println("请输入：(Q)表示退出");
            char key = myScanner.next().charAt(0);
            if (key == 'Q') {
                //以通知的方式结束A线程
                a.setLoop(false);
                System.out.println("b线程退出");
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}